from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.core.mail import send_mail
from utils.email_code import generate_email_code, verify_email_code
import re
from django.core.cache import cache
from djoser.views import UserViewSet
from account.serializers import PasswordChangeSerializer, ForgetPasswordSerializer, \
    CustomUserSerializer, AuthorSerializer
from rest_framework.decorators import action
from rest_framework.permissions import IsAuthenticated
from .models import CustomUser
from rest_framework import viewsets
from django.views.decorators.csrf import csrf_exempt
from djoser.views import UserViewSet
from rest_framework.decorators import action
from rest_framework import status
from rest_framework.response import Response
from .serializers import CustomPasswordResetConfirmSerializer
from .utils import generate_verification_code

def validate_email_format(email):
    """验证邮箱格式是否正确"""
    if not email:
        return False, "邮箱不能为空"
    if not re.match(r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$', email):
        return False, "邮箱格式不正确"
    return True, None


def check_email_code_frequency(email):
    """检查邮箱验证码发送频率"""
    last_sent_time = cache.get(f"email_code_sent_{email}")
    if last_sent_time:
        return False, "验证码已发送，请1分钟后再试"
    return True, None


def send_verification_email(email, code):
    """发送验证码邮件"""
    try:
        send_mail(
            subject='【Rice博客】注册验证码',
            message=f'您的验证码是：{code}，5分钟内有效。如非本人操作，请忽略此邮件。',
            from_email=None,
            recipient_list=[email],
        )
        cache.set(f"email_code_sent_{email}", True, timeout=60)
        return True, "验证码已发送，请查收邮件"
    except Exception as e:
        return False, f"发送邮件失败: {str(e)}"


class AuthorViewSet(viewsets.ModelViewSet):
    queryset = CustomUser.objects.all()
    serializer_class = AuthorSerializer

    def get_paginated_response(self, data):
        if self.request.query_params.get('size', '').lower() == 'all':
            return Response(data)
        return super().get_paginated_response(data)

class CustomUserViewSet(UserViewSet):
    """重写Djoser的用户视图集，确保验证码验证在用户创建过程中生效"""

    def create(self, request, *args, **kwargs):
        email = request.data.get('email')
        code = request.data.get('code')

        if not email or not code:
            return Response(
                {"code": "验证码不能为空"},
                status=status.HTTP_400_BAD_REQUEST
            )

        if not verify_email_code(email, code):
            return Response(
                {"code": "验证码错误或已过期"},
                status=status.HTTP_400_BAD_REQUEST
            )

        return super().create(request, *args, **kwargs)

    @action(detail=False, methods=['post'], permission_classes=[IsAuthenticated])
    def change_password(self, request):
        serializer = PasswordChangeSerializer(data=request.data)
        if serializer.is_valid():
            user = request.user
            if not user.check_password(serializer.validated_data['old_password']):
                return Response(
                    {'old_password': '旧密码不正确'},
                    status=status.HTTP_400_BAD_REQUEST
                )

            user.set_password(serializer.validated_data['new_password'])
            user.save()
            return Response({'message': '密码修改成功'}, status=status.HTTP_200_OK)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    @action(["post"], detail=False)
    def reset_password_confirm(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        if not serializer.is_valid():
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

        try:
            serializer.save()
            return Response(
                {"message": "密码重置成功"},
                status=status.HTTP_200_OK
            )
        except Exception as e:
            return Response(
                {"error": str(e)},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

    # 覆盖发送验证码接口
    @action(["post"], detail=False)
    def reset_password(self, request, *args, **kwargs):
        # 您的发送验证码逻辑
        email = request.data.get("email")
        # 验证邮箱格式
        is_valid, error_message = validate_email_format(email)
        if not is_valid:
            return Response({"error": error_message}, status=status.HTTP_400_BAD_REQUEST)

        # 检查发送频率
        can_send, error_message = check_email_code_frequency(email)
        if not can_send:
            return Response({"error": error_message}, status=status.HTTP_429_TOO_MANY_REQUESTS)

        # 生成并发送验证码
        code = generate_email_code(email)
        success, message = send_verification_email(email, code)

        if success:
            return Response({"message": message})
        return Response({"error": message}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        # if email:
        #     code = generate_verification_code(email)
        #     send_mail(code)  # 实现您的邮件发送
        # return Response(status=status.HTTP_204_NO_CONTENT)

# class SendEmailCodeView(APIView):
#     @csrf_exempt
#     def post(self, request):
#         email = request.data.get('email')
#
#         # 验证邮箱格式
#         is_valid, error_message = validate_email_format(email)
#         if not is_valid:
#             return Response({"error": error_message}, status=status.HTTP_400_BAD_REQUEST)
#
#         # 检查发送频率
#         can_send, error_message = check_email_code_frequency(email)
#         if not can_send:
#             return Response({"error": error_message}, status=status.HTTP_429_TOO_MANY_REQUESTS)
#
#         # 生成并发送验证码
#         code = generate_email_code(email)
#         success, message = send_verification_email(email, code)
#
#         if success:
#             return Response({"message": message})
#         return Response({"error": message}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
#
#
# class CheckEmailCodeView(APIView):
#     def post(self, request):
#         email = request.data.get('email')
#         code = request.data.get('code')
#
#         if not email or not code:
#             return Response({"error": "邮箱和验证码不能为空"}, status=status.HTTP_400_BAD_REQUEST)
#
#         if verify_email_code(email, code):
#             return Response({"valid": True, "message": "验证码有效"})
#         return Response({"valid": False, "error": "验证码无效或已过期"}, status=status.HTTP_400_BAD_REQUEST)
#
#
# class ForgetPasswordView(APIView):
#     def post(self, request):
#         serializer = ForgetPasswordSerializer(data=request.data)
#         if not serializer.is_valid():
#             return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
#
#         email = serializer.validated_data['email']
#         try:
#             user = CustomUser.objects.get(email=email)
#         except CustomUser.DoesNotExist:
#             return Response(
#                 {"error": "该邮箱未注册"},
#                 status=status.HTTP_404_NOT_FOUND
#             )
#
#         user.set_password(serializer.validated_data['new_password'])
#         user.save()
#
#         return Response(
#             {"message": "密码重置成功"},
#             status=status.HTTP_200_OK
#         )
#
#
